﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class Pages_UploadFotos : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string userId = Session["IdUsuario"].ToString(); 

        // Specify the path on the server to save the uploaded file to.
        string savePath = Path.GetDirectoryName(Request.PhysicalApplicationPath) + "\\Images\\Users\\" + userId + "\\PhotosUploads\\";        

        //Si no existe el directorio para el usuario lo creo
        if (!Directory.Exists(savePath))
            Directory.CreateDirectory(savePath);

        // Before attempting to save the file, verify that the FileUpload control contains a file.
        if (FilePhotoUpload.HasFile)
        {
            // Get the name of the file to upload.
            string fileName = Server.HtmlEncode(FilePhotoUpload.FileName);

            // Get the extension of the uploaded file.
            string extension = System.IO.Path.GetExtension(fileName);

            // Allow only files with .doc or .xls extensions to be uploaded.
            if ((extension == ".jpg") | (extension == ".png") | (extension == ".gif"))
            {
                // Append the name of the file to upload to the path.
                string[] filePaths = Directory.GetFiles(savePath, "*.jpg");
                string namePhoto = Convert.ToString(filePaths.Length + 1) + ".jpg";
                savePath += namePhoto;

                // Call the SaveAs method to save the uploaded file to the specified path.
                // This example does not perform all the necessary error checking.               
                // If a file with the same name already exists in the specified path, the uploaded file overwrites it.
                FilePhotoUpload.SaveAs(savePath);

                //Guarda la dirección de la foto en la DB
                SavePhotoInDataBase(namePhoto);

                Response.Redirect("VerUsuario.aspx?idUsuario=" + userId);
            }
            else
            {
                // Notify the user why their file was not uploaded.
                if (error.Visible == false)
                {
                    error.InnerHtml += "El archivo seleccionado no es una imagen";
                    error.Visible = true;
                }
            }
        }
    }

    private void SavePhotoInDataBase(string name)
    {
        string userId = Session["IdUsuario"].ToString();
        string urlPhoto = "../Images/Users/" + userId + "/PhotosUploads/" + name;
        string descripcion = Request["txtDescripcion"];
        UsuarioServices usuarioService = new UsuarioServices();
        usuarioService.SavePhoto(Convert.ToInt32(userId), urlPhoto, descripcion);
    }
}